package com.kehao.newcoder;

import org.junit.Test;

import java.util.Stack;

public class NC128Solution {

    public long maxWater(int[] arr) {
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        long area = 0;
        int current = 1;
        while ((!stack.isEmpty())&& current<arr.length){
            if(arr[current]<=arr[stack.peek()]||stack.size()<=1){
                stack.push(current);
                current++;
            }else {
                int pop = stack.pop();
                int height = 0;
                int width =0;
                height = Integer.max(0,Integer.min(arr[stack.peek()], arr[current])-arr[pop]);
                width = current-stack.peek()-1;
                area+=height*width;
            }
        }
        return area;
    }

    @Test
    public void test01() {
        int[] arr = new int[]{3,1,2,5,2,4};
        long result = maxWater(arr);
        System.out.println(result);
    }

    @Test
    public void test02() {
        int[] arr = new int[]{4,5,1,3,2};
        long result = maxWater(arr);
        System.out.println(result);
    }

    @Test
    public void test03() {
        int[] arr = new int[]{4,2,0,3,2,5};
        long result = maxWater(arr);
        System.out.println(result);
    }

    @Test
    public void test04() {
        int[] arr = new int[]{5,5,1,7,1,1,5,2,7,6};
        long result = maxWater(arr);
        System.out.println(result);
    }


    @Test
    public void test05() {
        int[] arr = new int[]{0,1,0,2,1,0,1,3,2,1,2,1};
        long result = maxWater(arr);
        System.out.println(result);
    }
}
